import { create } from 'zustand'
import BasicService from '@/interface/basic/service'
import storage from '@/utils/storage'
import type { UserType } from '@/interface/store/StoreDataType'
import type { LoginRequest } from '@/interface/basic/dto'
import encrypt from '@/utils/encrypt'
// @ts-ignore
const defineUserStore = create<UserType>((set, get) => ({
  username: 'user0001',
  realName: '未登录',
  nickname: '你猜',
  userType: 0,
  isLogin: false,
  password: '',
  deviceId: '',
  avatarUrl: '',
  id: '',
  // login: function (data: Partial<BasicDTO.LoginRequest>) {
  //   set({ deviceId: storage.get('deviceId') })
  //   data.encodePwd = encrypt.encrypePwd(data.password)
  //   data.deviceId = storage.get('deviceId')
  //   BasicService.login(data).then((res) => {
  //     if (res?.code == 0) {
  //       set({
  //         username: res?.data['username'],
  //         id: res?.data['id'],
  //         isLogin: true,
  //         realName: res?.data['realName'],
  //         nickname: res?.data['nickname'],
  //         userType: res?.data['userType'],
  //         avatarUrl: res?.data['avatarUrl']
  //       })
  //       storage.set('isLogin', '1')
  //       storage.set('username', res?.data['username'])
  //       storage.set('token', res?.data['token'])
  //       storage.set('loginTime', res?.data['loginTime'])
  //     } else {
  //     }
  //   })
  // },
  setCurrentUser: (value: UserType) => {
    set({
      username: value['username'],
      id: value['id'],
      isLogin: true,
      realName: value['realName'],
      nickname: value['nickname'],
      userType: value['userType'],
      avatarUrl: value['avatarUrl']
    })
  },
  loginByToken: function() {
    set({ deviceId: storage.get('deviceId') })
    const data: Partial<LoginRequest> = {}
    data.token = storage.get('token')
    BasicService.loginByToken().then((res) => {
      if (res?.code == 0) {
        set({
          username: res?.data['username'],
          id: res?.data['id'],
          isLogin: true,
          realName: res?.data['realName'],
          nickname: res?.data['nickname'],
          userType: res?.data['userType'],
          avatarUrl: res?.data['avatarUrl']
        })
        storage.set('isLogin', '1')
        storage.set('username', res?.data['username'])
        storage.set('loginTime', res?.data['loginTime'])
      } else {
      }
    })
  },
  //@ts-ignore
  setUsername: (value: string) => {
    set({ username: value })
  },
  //@ts-ignore
  setRealName: (value: string) => {
    set({ realName: value })
  }
}))
export default defineUserStore
